﻿using Microsoft.AspNetCore.SignalR;
using System.Collections.Concurrent;

namespace WebApplication1
{
    public class ChatHub : Hub
    {
        // 用户名与连接ID的映射
        private static ConcurrentDictionary<string, string> userConnMap = new();

        /// <summary>
        /// 用户连接后注册用户名
        /// </summary>
        public Task Register(string username)
        {
            userConnMap[username] = Context.ConnectionId;
            return Task.CompletedTask;
        }

        /// <summary>
        /// 一对一发送消息
        /// </summary>
        public Task SendPrivateMessage(string toUsername, string message)
        {
            if (userConnMap.TryGetValue(toUsername, out var toConnId))
            {
                string fromUsername = userConnMap.FirstOrDefault(x => x.Value == Context.ConnectionId).Key ?? "未知用户";
                string msgToSend = $"{fromUsername} {DateTime.Now}: {message}";
                return Clients.Client(toConnId).SendAsync("ReceiveMessage", msgToSend);
            }
            else
            {
                // 目标用户不在线
                return Clients.Caller.SendAsync("ReceiveMessage", $"系统: 用户 {toUsername} 不在线");
            }
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            // 移除断开连接的用户
            var user = userConnMap.FirstOrDefault(x => x.Value == Context.ConnectionId).Key;
            if (user != null)
            {
                userConnMap.TryRemove(user, out _);
            }
            return base.OnDisconnectedAsync(exception);
        }
    }
}
